package plugin

import (
	"dingbot/botapi"
	"dingbot/errhelp"
	"io"
	"net/http"
	"net/url"

	lua "github.com/yuin/gopher-lua"
)

func RegDingbotLuaFunc(L *lua.LState) {
	L.SetGlobal("dingbot_sendgroupmsg", L.NewFunction(func(l *lua.LState) int {
		botapi.SendGroupMsg(l.ToString(1), l.ToString(2))
		return 0
	}))
	L.SetGlobal("http_encode", L.NewFunction(func(l *lua.LState) int {
		l.Push(lua.LString(url.QueryEscape(l.ToString(1))))
		return 1
	}))
	L.SetGlobal("http_get", L.NewFunction(func(l *lua.LState) int {
		url_toget := l.ToString(1)
		res, err := http.Get(url_toget)
		if err != nil {
			l.Push(lua.LString(""))
			return 1
		}
		defer res.Body.Close()
		res_b, _ := io.ReadAll(res.Body)
		l.Push(lua.LString(string(res_b)))
		return 1
	}))
}

func RunLuaFunc(path string, func_name string) {
	L := lua.NewState()
	L.OpenLibs()
	RegDingbotLuaFunc(L)
	defer L.Close()
	err := L.DoFile(path)
	if !errhelp.Tag(err, "lua load") {
		return
	}
	err = L.CallByParam(lua.P{
		Fn:      L.GetGlobal(func_name),
		NRet:    0,
		Protect: true,
	})
	if !errhelp.Tag(err, "lua run") {
		return
	}
}

func RunLuaFuncWithParam(path string, func_name string, params ...lua.LValue) {
	L := lua.NewState()
	L.OpenLibs()
	RegDingbotLuaFunc(L)
	defer L.Close()
	err := L.DoFile(path)
	if !errhelp.Tag(err, "lua load") {
		return
	}
	err = L.CallByParam(lua.P{
		Fn:      L.GetGlobal(func_name),
		NRet:    len(params),
		Protect: true,
	}, params...)
	if !errhelp.Tag(err, "lua run") {
		return
	}
}
